package com.example.huawei.system.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.huawei.system.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "高德地图")
@RestController
@RequestMapping("/pace")
public class PlaceController {

    @ApiOperation(value = "周边搜索", notes = "周边搜索")
    @GetMapping("/around")
    public Result<?> around(@ApiParam(name = "pageNo", value = "当前页数", defaultValue = "1") @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                         @ApiParam(name = "pageSize", value = "每页记录数据", defaultValue = "4") @RequestParam(value = "pageSize", defaultValue = "4") Integer pageSize,
                         @ApiParam(name = "location", value = "中心点坐标 规则： 经度和纬度用\",\"分割，经度在前，纬度在后，经纬度小数点后不得超过6位", required = true) @RequestParam(value = "location") String location,
                         @ApiParam(name = "keywords", value = "查询关键字 规则：  只支持一个关键字") @RequestParam(value = "keywords", required = false) String keywords,
                         @ApiParam(name = "extensions", value = "此项默认返回基本地址信息；取值为all返回地址信息、附近 POI、道路以及道路交叉口信息。") @RequestParam(value = "extensions", required = false, defaultValue = "all") String extensions) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url = "https://restapi.amap.com/v3/place/around?location=" + location +
                    "&Key=5580de61489747645330fd8cb7498adc&radius=3000&offset=" + pageSize +
                    "&page=" + pageNo +
                    "&extensions=" + extensions;
            if (StringUtils.isNotBlank(keywords)) {
                url += "&keywords=" + keywords;
            }
            HttpGet get = new HttpGet(url);
            get.setHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse response = httpclient.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if ("1".equals(json.getString("status"))) {
                return Result.ok(json.getJSONArray("pois"));
            } else {
                return Result.error().message(json.getString("info"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message("未知错误");
        }
    }

    @ApiOperation(value = "天气", notes = "天气")
    @GetMapping("/weather")
    public Result<?> weather(@RequestParam(value = "location") String location,
                          @RequestParam(value = "days") Integer days) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url = "https://api.seniverse.com/v3/weather/daily" +
                    ".json?key=SZ-ruIja5oIXPRANV&language=zh-Hans&unit=c&start=0&days=" + days + "&location=" + location;
            HttpGet get = new HttpGet(url);
            get.setHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse response = httpclient.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (json.getString("status_code") == null) {
                return Result.ok(json.getJSONArray("results").getJSONObject(0).getJSONArray("daily"));
            } else {
                return Result.error().message(json.getString("status"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().message("未知错误");
        }
    }

    @ApiOperation(value = "车辆识别", notes = "车辆识别")
    @GetMapping("/ocr")
    public Result<?> ocr(@RequestParam("fileUrl")String fileUrl,
                         @RequestParam("topNum") Integer topNum,
                         @RequestParam("baikeNum")Integer baikeNum) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=Y9EFBprDVFJXPFCp0Wwo3mcd&client_secret=LHvqMBJfxaVpGEiyIZJOqSI4dbfkiRaw";
            HttpGet get = new HttpGet(url);
            get.setHeader("Content-Type", "application/json;charset=UTF-8");
            CloseableHttpResponse response = httpclient.execute(get);
            String result = EntityUtils.toString(response.getEntity(), "utf-8");
            JSONObject json = JSONObject.parseObject(result);
            if (json.getString("access_token") == null) {
                return Result.error().message("获取 access_token 失败");
            }
            String accessToken = json.get("access_token").toString();

            String postUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/car?access_token="+accessToken;
            HttpPost post = new HttpPost(postUrl);
            post.setHeader("Content-Type", "application/x-www-form-urlencoded");
            List<NameValuePair> formParams = new ArrayList<>();
            formParams.add(new BasicNameValuePair("url", fileUrl));
            formParams.add(new BasicNameValuePair("top_num", String.valueOf(topNum)));
            formParams.add(new BasicNameValuePair("baike_num", String.valueOf(baikeNum)));

            // 设置表单实体，指定UTF-8编码
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                    formParams,
                    StandardCharsets.UTF_8
            );
            post.setEntity(formEntity);
            response = httpclient.execute(post);
            result = EntityUtils.toString(response.getEntity(), "utf-8");
            json = JSONObject.parseObject(result);
            System.out.println(json);
            if (json.containsKey("result")) {
                return Result.ok(json.getJSONArray("result"));
            }

        }catch (Exception e){
            e.printStackTrace();
            return Result.error();
        }
        return Result.error();
    }
}
